package com.zhang.backend.web.controller;

import com.zhang.backend.model.domain.OrderProduct;
import com.zhang.backend.model.domain.Orders;
import com.zhang.backend.model.domain.Product;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.zhang.backend.common.JsonResponse;
import com.zhang.backend.service.OrderService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 前端控制器
 *
 * @author zyx
 * @version v1.0
 * @since 2021-12-22
 */
@Controller
@RequestMapping("/order")
public class OrderController {

    private final static Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private OrderService orderService;

    /**
     * 描述：根据Id 查询
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getById(@PathVariable("id") Long id) throws Exception {
        Orders orders = orderService.getById(id);
        return JsonResponse.success(orders);
    }

    /**
     * 描述：根据Id删除
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResponse deleteById(@PathVariable("id") Long id) throws Exception {
        orderService.removeById(id);
        return JsonResponse.success(null);
    }


    /**
     * 描述：根据Id 更新
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResponse updateOrder(@PathVariable("id") Long id,@RequestBody Orders orders) throws Exception {
        orders.setId(id);
        orderService.updateById(orders);
        return JsonResponse.success(200);
    }


    /**
     * 描述:创建Order
     */
//    @RequestMapping(value = "", method = RequestMethod.POST)
//    @ResponseBody
//    public JsonResponse create(@RequestBody Map<String, OrderProduct> map, @RequestBody Orders orders) throws Exception {
//        orderService.save(orders);
//        map.forEach((s, product) -> map.replace(s, product.setOrderId(orders.getId())));
//        List<OrderProduct> productList = new ArrayList<>(map.values());
//        orderService.insert(productList);
//        return JsonResponse.success(null);
//    }
    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse create1(@RequestBody List<OrderProduct> orderProductList, @RequestBody Orders orders) throws Exception {
        orderService.save(orders);
        orderProductList.forEach(x->x.setOrderId(orders.getId()));
        orderService.insert(orderProductList);
        return JsonResponse.success(null);
    }
}

